package org.esti.model.dao.impl;

import org.esti.model.Interview;
import org.esti.model.InterviewResult;
import org.esti.model.dao.InterviewDAO;
import org.esti.model.exceptions.InterviewDoesNotExistException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Artem Loginov (logart)
 */
@Repository
public class InterviewDAOimpl implements InterviewDAO {

    private static final Logger LOGGER = Logger.getLogger(InterviewDAOimpl.class.getName());

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true)
    @Override
    public List<Interview> getUserInterviews(long userId) {

        Query query = entityManager.createQuery(
                "SELECT interview FROM Interview interview WHERE interview.user.id=:userId"
        );
        query.setParameter("userId", userId);
        return (List<Interview>) query.getResultList();

    }

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true, noRollbackFor = InterviewDoesNotExistException.class)
    @Override
    public Interview get(long interviewId) {

        Interview interview = entityManager.find(Interview.class, interviewId);
        if (interview == null) {
            LOGGER.log(Level.INFO, "interview with id " + interviewId + " does not exist");
            throw new InterviewDoesNotExistException();
        } else {
            return interview;
        }

    }

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true)
    @Override
    public InterviewResult getInterviewResult(long interviewResultId) {
        return entityManager.find(InterviewResult.class, interviewResultId);
    }

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true)
    @Override
    public List<Interview> getAllInterview() {
        return entityManager.createQuery("SELECT interview FROM Interview interview").getResultList();
    }

    /**
     * {@inheritDoc}
     */
    @Transactional
    @Override
    public Interview create(Interview interview) {
        return entityManager.merge(interview);
    }
}
